package com.jplus.core.plugin.aspect;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.jplus.core.core.ApplicationContext;
import com.jplus.core.core.beans.BeanDefinition;
import com.jplus.core.core.beans.BeanKey;
import com.jplus.core.fault.InitializationError;
import com.jplus.core.plugin.ImportSelector;

/**
 * 
 * @author Yuanqy
 */
public class AspectConfigurationSelector implements ImportSelector {

	// private String DEF_ASPECT =
	// "com.jplus.core.imports.aspect.ProxyAspectConfiguration";

	@Override
	public String[] selectImports(ApplicationContext context) {
		try {
			List<BeanDefinition> list = context.getBeanDefinitions().listSortBeanDefinitions();
			Map<Aspect, BeanKey> expres = new HashMap<>();
			// 1.找到拦截类
			for (BeanDefinition bd : list) {
				if (bd.getBeanClass().isAnnotationPresent(Aspect.class)) {
					expres.put(bd.getBeanClass().getAnnotation(Aspect.class), bd.getBeanKey());
				}
			}
			// 2.找到被拦截类
			for (BeanDefinition bd : list) {
				for (Entry<Aspect, BeanKey> entry : expres.entrySet()) {
					Method[] ms = bd.getBeanClass().getDeclaredMethods();
					for (Method method : ms) {
						if (checkExpression(entry.getKey(), method)) {
							bd.addProxyList(entry.getValue()); // 添加代理关联,去重
							break;
						}
					}
				}
			}
			return new String[]{};
		} catch (

		Exception e) {
			throw new InitializationError(e);
		}
	}

	/**
	 * 判断:expre表达式 是否和类一致,精确到类名路径<br>
	 * TODO ....这个得改,改成支持正则表达式
	 */
	private boolean checkExpression(Aspect aspect, Method method) {
		return ExecutionKit.analysis(method, aspect);
	}

}
